package com.xzx.flink.streamapi.processfunction;

import com.xzx.flink.bean.ClickEvent;
import com.xzx.flink.streamapi.source.ClickSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;

/**
 * @version 1.0
 * @auther xinzhixuan
 * @date 2022/5/4 13:02
 */
public class KeyedProcessFunction_01_ProcessTime {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.addSource(new ClickSource())
                .keyBy(d -> true)
                .process(new KeyedProcessFunction<Boolean, ClickEvent, String>() {
                    @Override
                    public void processElement(ClickEvent value, KeyedProcessFunction<Boolean, ClickEvent, String>.Context ctx, Collector<String> out) throws Exception {
                        long currentProcessingTime = ctx.timerService().currentProcessingTime();
                        out.collect("数据到达，到达时间：" + new Timestamp(currentProcessingTime));
                        // 注册一个10秒后的定时器
                        ctx.timerService().registerProcessingTimeTimer(currentProcessingTime + 10 * 1000L);
                    }

                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<Boolean, ClickEvent, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
                        out.collect("定时器触发，触发时间：" + new Timestamp(timestamp));
                    }
                })
                .print();

        env.execute(KeyedProcessFunction_01_ProcessTime.class.getSimpleName());
    }
}
